/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
// eslint-disable-next-line
// @ts-ignore
// import store from 'src/vuex/store';

// import {
//     getStorage
// } from 'src/util/local_storage';


function createObjectURL(object: SafeAny) {
    return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}

function downloadFile(url: string, method: string, filename: string): void {

    let xhr = new XMLHttpRequest();
    let formData = new FormData();

    xhr.open(method, url); // url填写后台的接口地址，如果是post，在formData append参数（参考原文地址）
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.responseType = 'blob';
    xhr.onload = function () {
        // eslint-disable-next-line
        if (this.status === Number('200')) {
            // eslint-disable-next-line
            let blob = this.response;
            // filename = 'process.zip';

            if (!!(window as SafeAny).ActiveXObject || 'ActiveXObject' in window) {
                // @ts-ignore
                navigator.msSaveBlob(blob, filename);
            } else {
                let a = document.createElement('a');
                let url = createObjectURL(blob);
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);            // 释放url
            }
        }
    };

    xhr.send(formData);

}

function string2Blob(string: string) {
    return new Blob([string], {
        type: 'text/plain'
    });
}

function downloadStringFile(string: string, filename: string) {
    const blob = string2Blob(string)
    const d = document.createElement("a");
    // 设置下载内容
    d.href = window.URL.createObjectURL(blob);
    // 设置下载文件的名字
    d.download = filename;
    // 界面上隐藏该按钮
    d.style.display = "none";
    // 放到页面上
    document.body.appendChild(d);
    // 点击下载文件
    d.click();
    // 从页面移除掉
    document.body.removeChild(d);
    // 释放 URL.createObjectURL() 创建的 URL 对象
    window.URL.revokeObjectURL(d.href);
}

export {
    downloadFile,
    downloadStringFile
};
